import { Context } from 'koa';

/**
 * 租户状态枚举
 */
export enum TenantStatus {
  ACTIVE = 'active',
  INACTIVE = 'inactive',
  SUSPENDED = 'suspended',
  TRIAL = 'trial',
}

/**
 * 用户状态枚举
 */
export enum UserStatus {
  ACTIVE = 'active',
  INACTIVE = 'inactive',
  SUSPENDED = 'suspended',
}

/**
 * 用户类型枚举
 */
export enum UserType {
  SUPER_ADMIN = 'super_admin',
  TENANT_ADMIN = 'tenant_admin',
  TENANT_USER = 'tenant_user',
}

/**
 * 权限操作类型
 */
export enum PermissionAction {
  CREATE = 'create',
  READ = 'read',
  UPDATE = 'update',
  DELETE = 'delete',
  MANAGE = 'manage',
}

/**
 * 超级管理员专用租户ID
 */
export const SUPER_ADMIN_TENANT_ID = '000000';

/**
 * 扩展的 Koa Context，添加租户和用户信息
 */
export interface AppContext extends Context {
  state: {
    tenant?: {
      id: string;
      name: string;
      subdomain: string;
      planId: string;
      status: TenantStatus;
      config?: Record<string, any>;
      defaultPassword?: string;
    };
    user?: {
      id: string;
      tenantId: string | null;
      email: string;
      type: UserType;
      roleId: string | null;
    };
    [key: string]: any;
  };
}

/**
 * JWT Token Payload
 */
export interface JWTPayload {
  userId: string;
  tenantId: string | null;
  email: string;
  type: UserType;
  iat?: number;
  exp?: number;
}

/**
 * 分页参数
 */
export interface PaginationParams {
  page: number;
  pageSize: number;
  offset: number;
  limit: number;
}

/**
 * 分页结果
 */
export interface PaginatedResult<T> {
  data: T[];
  pagination: {
    total: number;
    page: number;
    pageSize: number;
    totalPages: number;
  };
}

/**
 * API 响应格式
 */
export interface ApiResponse<T = any> {
  success: boolean;
  data?: T;
  message?: string;
  code?: number;
  errors?: any[];
}

/**
 * 租户配置
 */
export interface TenantConfig {
  branding?: {
    logo?: string;
    primaryColor?: string;
    secondaryColor?: string;
  };
  locale?: {
    timezone?: string;
    language?: string;
    dateFormat?: string;
  };
  features?: Record<string, boolean>;
  [key: string]: any;
}

/**
 * 套餐功能配置
 */
export interface PlanFeatures {
  maxUsers: number;
  maxStorage: number; // in MB
  enableAnalytics: boolean;
  enableAPI: boolean;
  apiCallsPerMonth: number;
  enableCustomBranding: boolean;
  enablePrioritySupport: boolean;
  [key: string]: any;
}

/**
 * 数据库查询选项（带租户隔离）
 */
export interface TenantQueryOptions {
  tenantId: string;
  includeDeleted?: boolean;
  [key: string]: any;
}

/**
 * 操作日志类型
 */
export enum AuditAction {
  CREATE = 'create',
  UPDATE = 'update',
  DELETE = 'delete',
  LOGIN = 'login',
  LOGOUT = 'logout',
  ACTIVATE = 'activate',
  DEACTIVATE = 'deactivate',
  SUSPEND = 'suspend',
  RESTORE = 'restore',
}

/**
 * 操作日志接口
 */
export interface AuditLog {
  id: string;
  tenantId: string | null;
  userId: string;
  action: AuditAction;
  resource: string;
  resourceId: string | null;
  changes?: Record<string, any>;
  ipAddress?: string;
  userAgent?: string;
  createdAt: Date;
}

